/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package server;

/**
 *
 * @author User
 */

import engine.Player;
import engine.Singleton;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.Timer;
import java.util.logging.Level;
import java.util.logging.Logger;
import json.Protocol;
import org.json.simple.parser.ParseException;

public class OneForAllServer extends Thread implements Server
{
    private Socket socket;
    private BufferedReader in;
    private PrintWriter out;
    public Player p;
    private List<Player> client = Singleton.clients;
    private String str = null;
    public int pos;
    
      
    public void sendUser(String send, int newPos)
    {
      int number = -1;
      if (newPos == -1){
        number = pos;
      } else {
        number = newPos;
      }
       client.get(number).out.println(send);
    }
    
    public int getPos()
    {
      return pos;
    }
    
     @Override
  public Player getPlayer(int pos) {
    return client.get(pos);
  }
     
     public void move() throws IOException, ParseException{
         for (int i=0; i < client.size(); i++) {
           pos = i;
           p = client.get(i);
           socket = p.getSok();
           if (socket.getInputStream().available() > 0){
             str = p.in.readLine();
             System.out.println("Server comming: №" + i+ " " + str);
             new Protocol().get(str, this);
           }
            
         }
     }
    
    public void run()
    {
        while (true) {
      try
      {
        try
        {
          move();
        } catch (ParseException ex)
        {
          Logger.getLogger(OneForAllServer.class.getName()).log(Level.SEVERE, null, ex);
        }
      } catch (IOException ex)
      {
        Logger.getLogger(OneForAllServer.class.getName()).log(Level.SEVERE, null, ex);
      }
        }
    } 
}